package com.example.file_management.mapper.user;

import com.example.file_management.pojo.user.Auth;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
public interface AuthMapper {

    // 查询所有用户
    @Select("SELECT * FROM auth")
    List<Auth> findAllUsers();

    // 根据用户名查找用户
    @Select("SELECT * FROM auth WHERE username = #{username}")
    Auth findByUsername(String username);


    // 插入用户
    @Insert("INSERT INTO auth (username, password, phone_number, role_name, group_name, role_id, created_at, updated_at,group_id) " +
            "VALUES (#{username}, #{password}, #{phoneNumber}, #{roleName}, #{groupName}, #{roleId}, #{createdAt}, #{updatedAt},#{groupId})")
    @Options(useGeneratedKeys = true, keyProperty = "userId")
    int insertUser(Auth user);


    // 检查用户名是否存在
    @Select("SELECT COUNT(*) FROM auth WHERE username = #{username}")
    boolean isUsernameExists(String username);

    // 检查手机号是否存在
    @Select("SELECT COUNT(*) FROM auth WHERE phone_number = #{phoneNumber}")
    boolean isPhoneNumberExists(String phoneNumber);

    // 更新用户信息
    @Update("UPDATE auth SET username = #{username}, password = #{password}, phone_number = #{phoneNumber}, " +
            "group_id = #{groupId}, role_id = #{roleId}, updated_at = NOW() WHERE user_id = #{userId}")
    int updateUser(Auth user);

    // 检查手机号是否已被其他用户使用
    @Select("SELECT COUNT(*) FROM auth WHERE phone_number = #{phoneNumber} AND user_id != #{userId}")
    boolean isPhoneNumberExistsForOtherUser(@Param("phoneNumber") String phoneNumber, @Param("userId") Long userId);

    // 根据 role_id 查找该角色的所有用户
    @Select("SELECT * FROM auth WHERE role_id = #{roleId}")
    List<Auth> findUsersByRoleId(Long roleId);

    // 根据 group_id 查找该组的所有用户
    @Select("SELECT * FROM auth WHERE group_id = #{groupId}")
    List<Auth> findUsersByGroupId(Long groupId);

    // 更新用户所属组
    @Update("UPDATE auth SET group_id = #{groupId} WHERE user_id = #{userId}")
    int updateUserGroup(@Param("userId") Long userId, @Param("groupId") Long groupId);

    // 删除指定组内的所有用户
    @Delete("DELETE FROM auth WHERE group_id = #{groupId}")
    int deleteUsersByGroupId(Long groupId);

    // 解除所有该组的用户绑定（不删除用户，仅置空 group_id）
    @Update("UPDATE auth SET group_id = NULL WHERE group_id = #{groupId}")
    int unbindUsersFromGroup(Long groupId);

    // 检查用户ID是否存在
    @Select("SELECT COUNT(*) FROM auth WHERE user_id = #{userId}")
    boolean isUserIdExists(Long userId);

    // 删除用户
    @Delete("DELETE FROM auth WHERE user_id = #{userId}")
    int deleteUser(Long userId);
}